﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace TestPrint
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            printDocument1.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage);
            //printDialog1.Document = printDocument1;
            //printDialog1.ShowDialog();
            //if (printDialog1.ShowDialog() == DialogResult.OK)
            //  printDocument1.Print();
            PageSetupDialog pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.Document = printDocument1;
            pageSetupDialog.PageSettings.Landscape = true;
            pageSetupDialog.ShowDialog();
            
 
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
            printPreviewDialog.Document = printDocument1;
            try
            {
                printPreviewDialog.ShowDialog();
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
        {
            StringReader lineReader = new StringReader(textBox.Text);
            Graphics g = e.Graphics; //获得绘图对象
            float linesPerPage = 0; //页面的行号
            float yPosition = 0;   //绘制字符串的纵向位置
            int count = 0; //行计数器
            float leftMargin = e.MarginBounds.Left; //左边距
            float topMargin = e.MarginBounds.Top; //上边距
            string line = null; 
            Font printFont = this.textBox.Font; //当前的打印字体
            SolidBrush myBrush = new SolidBrush(Color.Black);//刷子
            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g);//每页可打印的行数
            //逐行的循环打印一页
            while(count < linesPerPage && ((line=lineReader.ReadLine()) != null))
            {
               yPosition = topMargin + (count * printFont.GetHeight(g));
               g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
               count++;
            }

             if(line != null)
                e.HasMorePages = true;
            else
                e.HasMorePages = false; 
        }
    }
}